/*
 * @Author: CodeHare
 * @Date: 2023-10-16 19:16:04
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-23 17:46:33
 * @Description:  空调参数设置
 */
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/model/device_obj/spec/double_spec.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/energy_manage_set/energy_manage_set_view.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/air_condition_setting/air_condition_setting_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

class AirConditionSettingPage extends GetView<AirConditionSettingController> {
  const AirConditionSettingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AirConditionSettingController>(
      builder: (_) => Scaffold(
        appBar: AppBar(
          title: Text(
            ResKey.parameterSets.tr,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
          leading: GestureDetector(
            onTap: () => Get.back(result: true),
            child: Icon(
              Platform.isAndroid ? Icons.arrow_back : Icons.arrow_back_ios,
              color: Colour.black,
            ),
          ),
        ),
        body: controller.editType != -1
            ? EnergyManageSetView(
                deviceId: controller.deviceId.toString(),
                servicesList: [
                  controller.editType == 1
                      ? controller.model.fixedParameterModel!
                      : controller.model.runParameterModel!
                ],
                dataSource: controller.model.deviceData,
                cancelCallBack: () {
                  controller.editType = -1;
                  controller.update();
                },
                confirmCallBack: controller.afterConfirmSet,
              )
            : ListView(
                children: <Widget>[
                  _generateRunningList(context),
                  _generateConstantsList(context),
                ],
              ),
      ),
    );
  }

  Widget _generateRunningList(BuildContext context) {
    var runParameterModel = controller.model.runParameterModel;
    var deviceData = controller.model.deviceData;

    if (runParameterModel == null || runParameterModel.outputData.isEmpty) {
      return Container();
    } else {
      List timeList = controller.model.deviceData['runningTimeFrame'] ?? [];

      if (controller.bwtAirSetting) {
        for (var i = 1; i < 6; i++) {
          timeList.add({}..putIfAbsent('TimeFrame',
              () => deviceData['runningTimeFrame$i'] ?? '     -     '));
        }
      } else if (deviceData['runningTimeFrame'] == null ||
          deviceData['runningTimeFrame'].isEmpty ||
          deviceData['runningTimeFrame'].length == 0) {
        controller.handlerEmpty(deviceData);
      }

      return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          if (index == 0) {
            return Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 10.h),
                  color: Colour.white,
                  height: 50.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(left: 16.w),
                        child: Text(
                          'siteMonitor.runningParameterSet'.tr,
                          style: TextStyle(
                            color: Colour.mainTextColor,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.sp,
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => controller.onClick(0),
                        child: Padding(
                          padding: EdgeInsets.only(
                            right: 16.w,
                          ),
                          child: Text(
                            ResKey.deviceParameterSetting.tr,
                            style: TextStyle(
                              color: Colour.primaryColor,
                              fontWeight: FontWeight.bold,
                              fontSize: 16.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(
                  height: 1,
                  color: Colour.dividerColor,
                  indent: 16.w,
                  endIndent: 16.w,
                ),
              ],
            );
          } else {
            Map item;
            if (timeList.isEmpty) {
              item = {'TimeFrame': null};
            } else {
              item = timeList[index - 1];
            }

            return Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              height: 50.h,
              width: double.infinity,
              color: Colour.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      runParameterModel.outputData[index - 1].name,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colour.lightTextColor,
                      ),
                    ),
                  ),
                  Visibility(
                    // visible: !controller.isHidden,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          color: Colour.white,
                          margin: EdgeInsets.only(right: 2.w),
                          alignment: Alignment.center,
                          child: Text(
                            item["TimeFrame"]?.toString().substring(0, 5) ??
                                '--',
                            style: TextStyle(
                              color: controller.connectStatus ==
                                      ConnectStatusType.off
                                  ? Colour.offlineTextColor
                                  : Colour.mainTextColor,
                              fontSize: 14.sp,
                            ),
                          ),
                        ),
                        Visibility(
                          visible: !controller.isHidden,
                          child: const Text(
                            "－",
                            style: TextStyle(color: Colour.lightTextColor),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 4.w),
                          alignment: Alignment.center,
                          child: Text(
                            item["TimeFrame"]?.toString().substring(6, 11) ??
                                "",
                            style: TextStyle(
                              color: controller.connectStatus ==
                                      ConnectStatusType.off
                                  ? Colour.offlineTextColor
                                  : Colour.mainTextColor,
                              fontSize: 14.sp,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }
        },
        itemCount: timeList.isEmpty ? 2 : timeList.length + 1,
      );
    }
  }

  Widget _generateConstantsList(BuildContext context) {
    /// 物模型的数据模型
    var fixedParamsModel = controller.model.fixedParameterModel;

    if (fixedParamsModel == null || fixedParamsModel.outputData.isEmpty) {
      return Container();
    } else {
      return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          if (index == 0) {
            return Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 10.h),
                  color: Colour.white,
                  height: 50.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(left: 16.w),
                        child: Text(
                          ResKey.deviceRunFixedValueSetting.tr,
                          style: TextStyle(
                            color: Colour.mainTextColor,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.sp,
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => controller.onClick(1),
                        child: Padding(
                          padding: EdgeInsets.only(right: 16.w),
                          child: Text(
                            ResKey.deviceParameterSetting.tr,
                            style: TextStyle(
                              color: Colour.primaryColor,
                              fontWeight: FontWeight.bold,
                              fontSize: 16.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(
                  height: 1,
                  color: Colour.dividerColor,
                  indent: 16.w,
                  endIndent: 16.w,
                ),
              ],
            );
          } else {
            var outputModel = fixedParamsModel.outputData[index - 1];
            var spec = outputModel.dataType.specs as DoubleSpec;

            return ItemWidget(
              isRequired: controller.editType == 1 ? true : false,
              outputModel.name,
              titleColor: Colour.lightTextColor,
              TextEditingController(
                  text:
                      controller.model.deviceData[outputModel.id]?.toString() ??
                          ''),
              unitString: spec.unit ?? '',
              isShowDivider: true,
              titleFont: 14.sp,
              unitTextColor: controller.connectStatus == ConnectStatusType.off
                  ? Colour.offlineTextColor
                  : Colour.mainTextColor,
              inputTextColor: controller.connectStatus == ConnectStatusType.off
                  ? Colour.offlineTextColor
                  : Colour.mainTextColor,
            );
          }
        },
        itemCount: fixedParamsModel.outputData.length + 1,
      );
    }
  }
}
